package com.example.yimai.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.example.yimai.service.OrderService;
import com.example.yimai.service.impl.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private OrderService orderService;

    @RequestMapping("/pay/{id}")
    public String pay(@PathVariable String id) {
        return alipayService.createAlipay(id,"测试");
    }

    @RequestMapping("/refund")
    public String refund(@RequestParam String orderId){
        return alipayService.refund(orderId);
    }

    @RequestMapping("/notify")
    public String returnNotify(HttpServletRequest request){

        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();

        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        try {
            String alipayPrivateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCZASqLOEIFLQNtincvzAFusOevkhO2wHbVTMwU1IQ89Pa8MK4U8zMG5eLTNkgmOpMMcaLKsPfLOFsZ8EIIf2Jj+KItpmaxpMEaV0gF8+IT42s6YN/C/S4Js/NNV7xJyZZevlKC/6SMSvajYAobE2NlhFk01C3rMyupvOCZUp901YgnTPgGeU8WBowCoY0fcY8LbDraVOoHbnR04LMbJG1PCYXpwy8cMCxQfETKTpNDr6Iq4OdhzYOQy9rVeBLIPSQzpYp19hYjKPmgdfEGDmPVhfsurJ17fWJxB7KjBOUflwQR2Frd/NX01wxij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Usv3P6vJV64ZuxlFjAoGAFrYsEuYm0rP9xjUruIMghomIx/ieYGE0arkenM14erzwURkUr7PWSTqTAMdL0AH/EN+X94CNLcSPs8Wk+lSzt0JfBsUUzKEwREBJfP9SNT2jzxQczo71OEp3tRp4TaziBtF4lSeIiCN3Y5Mt/jFszU0nzZZf6F1n32K21molebI=";
            boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayPrivateKey, "UTF-8", "RSA2");
            if (signVerified) {
                String tradeStatus = params.get("trade_status");
                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                    String orderId = params.get("out_trade_no");
                    orderService.pay(orderId);
                }
                return "success";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fail";
    }

}
